<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-button type="primary" plain @click="dialogVisible = true">创建账号</el-button>
        <el-button type="success" plain @click="showModifyForm">重置密码</el-button>
        <el-button type="info" icon="el-icon-delete" plain @click="removeRecord">删除</el-button>
        <el-button type="success" plain @click="showModifyRoleForm">修改角色</el-button>
        <el-input
          placeholder="请输入手机号、用户名、账号"
          suffix-icon="el-icon-search"
          v-model="searchVal" style="width: 150px;">
        </el-input>
        <el-button type="info" plain @click="searchClk">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          ref="envGrid"
          border
          highlight-current-row
          @row-click="selectRow"
          @sort-change="sortClick"
          :data="tableData2"
          style="width: 100%">
          <el-table-column
            prop="id"
            label="主键"
            sortable="custom"
            width="250">
          </el-table-column>
          <el-table-column
            prop="usercode"
            sortable="custom"
            label="usercode">
          </el-table-column>
          <el-table-column
            prop="username"
            sortable="custom"
            label="名称">
          </el-table-column>
          <el-table-column
            prop="mobile"
            sortable="custom"
            label="手机号">
          </el-table-column>
          <el-table-column
            prop="state"
            label="状态">
          </el-table-column>
          <el-table-column
            prop="createtime"
            sortable="custom"
            label="创建时间">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span>{{ scope.row.createtime | formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="roleSet"
            label="角色">
            <template slot-scope="scope">
              <el-tag :key="idx" v-for="(role,idx) in scope.row.roleSet">{{role.text}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[10,50,100]"
          :page-size="10"
          layout="sizes, prev, pager, next"
          :total="totalCount">
        </el-pagination>
      </el-col>
    </el-row>

    <!--新建账号-->
    <el-dialog
      title="账号信息"
      :visible.sync="dialogVisible"
      :before-close="handleAdminClose"
      width="30%">
      <el-form ref="adminForm" :model="adminForm" label-width="100px" :rules="adminFormRules">
        <el-form-item label="名称" prop="username">
          <el-input v-model="adminForm.username"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="usercode">
          <el-input v-model="adminForm.usercode"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="adminForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdminForm()">确 定</el-button>
        <el-button @click="resetForm('adminForm')">重 置</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible.sync="resetPwdDlgShow"
      :before-close="handleResetPwdClose"
      width="30%">
      <el-form ref="resetPwdForm" :model="resetPwdForm" label-width="100px" :rules="resetPwdFormRules">
        <el-form-item label="密码" prop="password">
          <el-input v-model="resetPwdForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResetPwdForm()">确 定</el-button>
        <el-button @click="resetForm('resetPwdForm')">重 置</el-button>
      </div>
    </el-dialog>
    <!--修改角色-->
    <el-dialog
      title="修改角色"
      :visible.sync="modifyRoleDlgShow"
      width="600px">
      <el-transfer
        v-model="roleValues"
        :data="roleDatas"
        :titles="['未选择角色', '已选择角色']"
        :button-texts="['减少', '增加']"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitModifyRole()">确 定</el-button>
        <el-button @click="modifyRoleDlgShow=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  import { post, formatDate, formRules, adminRoles } from "../../../util/util";

  export default {
    components: {
      ElCol,
      ElRow
    },
    methods: {
      submitModifyRole () {
        if (this.roleValues.length > 0) {
          let roles = "";
          for (let i = 0; i < this.roleValues.length; i++) {
            roles += this.roleValues[i];
            if (i !== (this.roleValues.length - 1)) {
              roles += ",";
            }
          }
          let userId = this.selectRows[0].id;
          let that = this;
          post("/admin/sysmgr/changeRole.do", {userId: userId, roles: roles}).then(function (data) {
            if (data.data.success) {
              that.modifyRoleDlgShow = false;
              that.requestData();
            } else {
              that.$alert(data.data.errorMsg);
            }
          });
        }
      },
      selectRow (row) {
        this.$refs.envGrid.setCurrentRow(row);
        let idx = this.selectRows.indexOf(row);
        if (idx >= 0) {
          this.$refs.envGrid.clearSelection();
          this.selectRows.pop(row);
        } else {
          this.selectRows.push(row);
        }
      },
      handleSizeChange (val) {
        this.gridQueryParam.pageSize = val;
        this.requestData();
      },
      handleCurrentChange (val) {
        this.gridQueryParam.page = val;
        this.requestData();
      },
      showModifyForm () {
        if (this.selectRows.length > 0) {
          this.resetPwdForm.id = this.selectRows[0].id;
          this.resetPwdDlgShow = true;
        }
      },
      showModifyRoleForm () {
        if (this.selectRows.length > 0) {
          if (this.roleDatas.length === 0) {
            let roles = adminRoles();
            for (let i = 0; i < roles.length; i++) {
              this.roleDatas.push({key: roles[i].name, label: roles[i].text});
            }
          }
          this.roleValues = [];
          let roleSet = this.selectRows[0].roleSet;
          for (let i = 0; i < roleSet.length; i++) {
            this.roleValues.push(roleSet[i].name);
          }
          this.modifyRoleDlgShow = true;
        }
      },
      removeRecord () {
        let that = this;
        if (this.selectRows.length > 0) {
          let row = this.selectRows[0];
          this.$confirm("您确认要删除这个记录吗").then(function () {
            post("/admin/sysmgr/deleteAccount.do", {userId: row.id}).then(function (data) {
              if (data.data.success) {
                that.requestData();
              } else {
                that.$alert(data.data.errorMsg);
              }
            });
          });
        }
      },
      sortClick (col) {
        this.gridQueryParam.sort = col.prop;
        this.gridQueryParam.order = ((col.order === "ascending") ? "asc" : "desc");
        this.requestData();
      },
      searchClk () {
        this.requestData();
      },
      requestData () {
        let that = this;
        let queryParam = that.gridQueryParam;
        let params = {
          "pageUtil.sort": !queryParam.sort ? "id" : queryParam.sort,
          "pageUtil.order": !queryParam.order ? "asc" : queryParam.order,
          "pageUtil.pageId": !queryParam.page ? 1 : queryParam.page,
          "pageUtil.pageSize": !queryParam.pageSize ? 10 : queryParam.pageSize,
          "pageUtil.condRelat": queryParam.condRelat
        };
        if (this.searchVal) {
          params.mobile = that.searchVal;
          params.usercode = that.searchVal;
          params.username = that.searchVal;
          params["pageUtil.condRelat"] = "or";
        } else {
          params["pageUtil.condRelat"] = "and";
        }
        post("/admin/sysmgr/adminlist.do", params).then((res) => {
          if (res) {
            let data = res.data.data;
            that.tableData2 = data.rows;
            that.totalCount = data.total;
          }
        });
      },
      submitResetPwdForm () {
        let that = this;
        this.$refs["resetPwdForm"].validate((valid) => {
          if (valid) {
            post("/admin/sysmgr/resetPwd.do", {
              userId: that.resetPwdForm.id,
              password: that.resetPwdForm.password
            }).then(function (data) {
              if (data.data.success) {
                that.$alert("重置密码成功");
                that.handleResetPwdClose();
              } else {
                that.$alert(data.data.errorMsg);
              }
            });
          }
        });
      },
      submitAdminForm () {
        let that = this;
        this.$refs["adminForm"].validate((valid) => {
          if (valid) {
            post("/admin/sysmgr/createAdmin.do", {
              mobile: that.adminForm.mobile,
              username: that.adminForm.username,
              usercode: that.adminForm.usercode,
              password: that.adminForm.password,
              role: that.adminForm.role
            }).then(function (data) {
              if (data.data.success) {
                that.resetForm("adminForm");
                that.dialogVisible = false;
                that.requestData();
              } else {
                that.$alert(data.data.errorMsg);
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      resetForm (formName) {
        this.$refs[formName].resetFields();
      },
      handleAdminClose () {
        this.$refs["adminForm"].resetFields();
        this.dialogVisible = false;
      },
      handleResetPwdClose () {
        this.$refs["resetPwdForm"].resetFields();
        this.resetPwdDlgShow = false;
      }
    },
    data () {
      return {
        modifyRoleDlgShow: false,
        roleValues: [],
        roleDatas: [],
        gridQueryParam: {
          page: 1,
          pageSize: 10,
          sort: "id",
          order: "asc",
          condRelat: "and"
        },
        searchVal: "",
        resetPwdForm: {
          id: "",
          password: ""
        },
        resetPwdDlgShow: false,
        resetPwdFormRules: formRules(["password"]),
        adminForm: {
          id: "",
          username: "",
          usercode: "",
          mobile: "",
          password: "",
          role: ""
        },
        roleOptions: [{
          value: "admin",
          label: "管理员"
        }, {
          value: "omni",
          label: "客服人员"
        }, {
          value: "roadLineMgr",
          label: "路线运营"
        }, {
          value: "activityMgr",
          label: "活动运营"
        }],
        adminFormRules: formRules(["username", "usercode", "mobile", "password", "role"]),
        dialogVisible: false,
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        tableData2: [],
        selectRows: []
      };
    },

    created () {
      this.requestData();
    },
    filters: {
      formatDate (time) {
        var date = new Date(time);
        return formatDate(date, "yyyy-MM-dd hh : mm");
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .el-table__body tr.current-row > td {
    background: #ffe48d !important;
  }
</style>
